package com.hxx.day2.action;

import org.junit.Test;

import java.io.*;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystemNotFoundException;

public class TestException {

    /**
     * 运行时异常
     * java.lang.ArithmeticException: / by zero
     */
    @Test
    public void test1() {
        int x = 10;
        int y = 0;
        int z = x/y;
    }

    /**
     * 一般性异常、受控异常、编译期异常
     */
    @Test
    public void test5() {
        try {
            InputStream in = new FileInputStream("d:/a.txt");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用try-catch处理
     */
    @Test
    public void test2() {
        try {
            int x = 10;
            int y = 0;
            int z = x/y;
            System.out.println("====执行的代码===");
        }catch (ArithmeticException e){
            System.out.println("-----one---->>"+e.getMessage());
        }catch (Exception e){
            System.out.println("----two----->>"+e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * finally代码无论如何都必须执行
     */
    @Test
    public void test3() {
        try {
            System.out.println(2/0);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //数据库关闭链接：释放资源
            System.out.println("----finally----");
        }
    }

    /**
     * 异常新编写方式
     */
    @Test
    public void test4() {
        InputStream in = null;
        try {
            in = new FileInputStream("d:/a.txt");
        } catch (FileNotFoundException | FileSystemNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 自动关闭
     */
    @Test
    public void test6() {
        try(InputStream in = new FileInputStream("d:/a.txt");
            OutputStream out = new FileOutputStream("d:/b.txt");) {

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 使用finally：笔试题
     */
    @Test
    public void test7() {
        int a =getData();
    }
    private int getData() {
        int a = 10;
        try {
            //已经在弹栈中了，finally代码块中的代码会被执行，
            // 但是不能改变try代码块中的变量
            return a;
        } finally {
            a += 20;
        }
    }
}













